package com.hjzd.ai.smartpractice.util;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

public class SequenceAudioInputStream extends AudioInputStream {

    private List<AudioInputStream> audioInputStreams;
    private int currentStreamIndex;

    public SequenceAudioInputStream(AudioFormat audioFormat, List<AudioInputStream> audioInputStreams) {
        super(new ByteArrayInputStream(new byte[0]), audioFormat, AudioSystem.NOT_SPECIFIED);
        this.audioInputStreams = audioInputStreams;
        this.currentStreamIndex = 0;
    }

    @Override
    public int read() throws IOException {
        int result;
        while (true) {
            if (currentStreamIndex >= audioInputStreams.size()) {
                return -1;
            }
            result = audioInputStreams.get(currentStreamIndex).read();
            if (result != -1) {
                return result;
            }
            currentStreamIndex++;
        }
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int result;
        while (true) {
            if (currentStreamIndex >= audioInputStreams.size()) {
                return -1;
            }
            result = audioInputStreams.get(currentStreamIndex).read(b, off, len);
            if (result != -1) {
                return result;
            }
            currentStreamIndex++;
        }
    }

    @Override
    public long skip(long n) throws IOException {
        long result;
        while (true) {
            if (currentStreamIndex >= audioInputStreams.size()) {
                return 0;
            }
            result = audioInputStreams.get(currentStreamIndex).skip(n);
            if (result != 0) {
                return result;
            }
            currentStreamIndex++;
        }
    }

    @Override
    public int available() throws IOException {
        if (currentStreamIndex >= audioInputStreams.size()) {
            return 0;
        }
        return audioInputStreams.get(currentStreamIndex).available();
    }

    @Override
    public void close() throws IOException {
        for (AudioInputStream stream : audioInputStreams) {
            stream.close();
        }
    }

    @Override
    public boolean markSupported() {
        return false;
    }

    @Override
    public void mark(int readlimit) {
    }

    @Override
    public void reset() throws IOException {
        throw new IOException("mark/reset not supported");
    }
}